# Maintainer: Alexey Pavlov <alexpux@gmail.com>

_realname=dlfcn
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=1.3.0
pkgrel=2
pkgdesc="A wrapper for dlfcn to the Win32 API (mingw-w64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clang32')
url="https://github.com/dlfcn-win32/dlfcn-win32"
license=('MIT')
makedepends=("${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-ninja")
options=('strip' 'staticlibs')
source=(${_realname}-${pkgver}.tar.gz::https://github.com/dlfcn-win32/dlfcn-win32/archive/v${pkgver}.tar.gz)
sha256sums=('24c69d43ddc9243fd2639a07495a7e0714278e8d3d0e124afdbab892dbb4a92d')

prepare() {
  cd "${srcdir}/dlfcn-win32-${pkgver}"
}

build() {
  for SHARED in YES NO; do
    [[ -d "${srcdir}/build-${MSYSTEM}-${SHARED}" ]] && rm -rf "${srcdir}/build-${MSYSTEM}-${SHARED}"
    mkdir -p "${srcdir}/build-${MSYSTEM}-${SHARED}" && cd "${srcdir}/build-${MSYSTEM}-${SHARED}"

    declare -a extra_config
    if check_option "debug" "n"; then
      extra_config+=("-DCMAKE_BUILD_TYPE=Release")
    else
      extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
    fi

    MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
      ${MINGW_PREFIX}/bin/cmake.exe \
        -GNinja \
        -DBUILD_SHARED_LIBS=${SHARED} \
        -DCMAKE_INSTALL_PREFIX="${MINGW_PREFIX}"  \
        -DBUILD_TESTS=ON \
        ../${_realname}-win32-${pkgver}
    ${MINGW_PREFIX}/bin/cmake.exe --build .
  done
}

check() {
  for SHARED in YES NO; do
    msg "Test: Mingw host:       ${MINGW_CHOST}"
    msg "Test: MSYSTEM variable: ${MSYSTEM}"
    msg "Test: Shared version:   ${SHARED}"
    cd "${srcdir}/build-${MSYSTEM}-${SHARED}"
    cmake --build . --target test
  done
}

package() {
  for SHARED in YES NO; do
    cd "${srcdir}/build-${MSYSTEM}-${SHARED}"
    DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake.exe --install .
  done
  cd ${srcdir}/dlfcn-win32-${pkgver}
  install -Dm644 README.md "${pkgdir}${MINGW_PREFIX}/share/doc/${_realname}/README.md"
  install -Dm644 COPYING "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE"
  # We do not want transitive dependencies on libdll.dll so remove it
  # We installed static last so the CMake files pertain to a static
  # build already.
  rm -f ${pkgdir}${MINGW_PREFIX}/bin/libdl.dll
  rm -f ${pkgdir}${MINGW_PREFIX}/lib/libdl.dll.a
}
